﻿
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Tween the widget's size.
/// </summary>

[RequireComponent(typeof(Image))]
[AddComponentMenu("UGUI/Tween/Tween Fill Amount")]
public class UGUITweenFillAmount : UGUITweener
{
    public override object fromValue { get { return from; } set { from = (float)value; } }
    public override object toValue { get { return to; } set { to = (float)value; } }

    public float from = 0;
	public float to = 1;
	public bool updateTable = false;

    Image mWidget;

    public Image cachedWidget { get { if (mWidget == null) mWidget = GetComponent<Image>(); return mWidget; } }

    /// <summary>
    /// Tween's current value.
    /// </summary>
    public float value
    {
        get
        {
            return cachedWidget.fillAmount;
        }
        set
        {
            cachedWidget.fillAmount = value;
        }
    }

    /// <summary>
    /// Tween the value.
    /// </summary>
    protected override void OnUpdate (float factor, bool isFinished)
	{
		value = from * (1f - factor) + to * factor;
	}

	/// <summary>
	/// Start the tweening operation.
	/// </summary>

	static public UGUITweenFillAmount Begin (Image widget, float duration, int fillAmount)
	{
        UGUITweenFillAmount comp = UGUITweener.Begin<UGUITweenFillAmount>(widget.gameObject, duration);
        comp.from = (int)widget.fillAmount;
		comp.to = fillAmount;

		if (duration <= 0f)
		{
			comp.Sample(1f, true);
			comp.enabled = false;
		}

		return comp;
	}

	[ContextMenu("Set 'From' to current value")]
	public override void SetStartToCurrentValue () { from = value; }

	[ContextMenu("Set 'To' to current value")]
	public override void SetEndToCurrentValue () { to = value; }

	[ContextMenu("Assume value of 'From'")]
	void SetCurrentValueToStart () { value = from; }

	[ContextMenu("Assume value of 'To'")]
	void SetCurrentValueToEnd () { value = to; }
}
